package cn.daniellee.plugin.rs.listener;

import cn.daniellee.plugin.rs.RestrictedShop;
import java.text.DecimalFormat;
import cn.daniellee.plugin.rs.core.ShopCore;
import cn.daniellee.plugin.rs.menu.*;
import cn.daniellee.plugin.rs.model.PlayerData;
import cn.daniellee.plugin.rs.model.Shop;
import cn.daniellee.plugin.rs.model.ShopItem;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

public class MenuListener implements Listener {

    @EventHandler
    public void onInventoryClick(InventoryClickEvent e) {
        if (!(e.getWhoClicked() instanceof Player)) return;
        Player player = (Player) e.getWhoClicked();
        Inventory menu = e.getInventory();
        if (menu.getHolder() != null && menu.getHolder() instanceof ShopMenu.ShopMenuHolder) {
            e.setCancelled(true);
            PlayerData playerData = ShopCore.TRADING.get(player.getName());
            if (playerData != null) {
                Shop shop = ShopCore.SHOPS.get(playerData.getShop());
                if (shop != null) {
                    if (e.getClick().isLeftClick()) {
                        int origin = playerData.getIndexList().length > 14 ? 13 : 22;
                        // 计算当前行的中心点
                        int lineCenter = origin + (e.getRawSlot() - origin + 4) / 9 * 9;
                        // 计算该槽位对应的顺序
                        int index = (e.getRawSlot() - origin + 4) / 9 * 7 + (e.getRawSlot() - lineCenter >= 0 ? (e.getRawSlot() - lineCenter) * 2 : Math.abs(e.getRawSlot() - lineCenter) * 2 - 1);
                        if (e.getCurrentItem() != null && index >= 0 && index < playerData.getIndexList().length) {
                            // 计算可售数量
                            int sellableNumber = (playerData.getPurchaseNumbers()[index] * (100 + playerData.getPercentage()) / 100) - playerData.getSoldNumbers()[index];
                            if (sellableNumber > 0) {
                                // 获取所售物品信息
                                ShopItem shopItem = shop.getPurchaseItems().get(playerData.getIndexList()[index]);
                                // 计算每个出售的价格衰减
                                double attenuation = ((double) (shopItem.getPriceRange()[1] - shopItem.getPriceRange()[0])) / ((double) (shopItem.getQuantityRange()[1] * (100 + playerData.getPercentage()) / 100));
                                if (e.getClick().isShiftClick()) {
                                    double maxPrice = ((double) shopItem.getPriceRange()[1]) - attenuation * ((double) playerData.getSoldNumbers()[index]);
                                    int totalSold = 0;
                                    for (ItemStack itemStack : player.getInventory()) {
                                        if (itemStack != null && itemStack.getType().toString().equals(shopItem.getMaterial()) && (itemStack.getItemMeta() == null || !itemStack.getItemMeta().hasCustomModelData() || itemStack.getItemMeta().getCustomModelData() == shopItem.getCustomerModelData())) {
                                            // 如果这些不够，直接清零
                                            if (itemStack.getAmount() <= sellableNumber) {
                                                totalSold += itemStack.getAmount();
                                                sellableNumber -= itemStack.getAmount();
                                                itemStack.setAmount(0);
                                            } else {
                                                itemStack.setAmount(itemStack.getAmount() - sellableNumber);
                                                totalSold += sellableNumber;
                                                sellableNumber = 0;
                                                break;
                                            }
                                        }
                                    }
                                    if (totalSold > 0) {
                                        // 计算总价
                                        double minPrice = ((double) shopItem.getPriceRange()[1]) - attenuation * ((double) (playerData.getSoldNumbers()[index] + totalSold));
                                        double totalPrice = (maxPrice + minPrice) / 2 * totalSold;
                                        playerData.getSoldNumbers()[index] += totalSold;
                                        // 发钱
                                        Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), shop.getPayTemplate().replace("{player}", player.getName()).replace("{amount}", new DecimalFormat("#.00").format(totalPrice)));
                                        e.setCurrentItem(ShopCore.generateShopItem(shopItem, sellableNumber, playerData.getSoldNumbers()[index], playerData.getPercentage()));
                                    } else player.sendMessage((RestrictedShop.getInstance().getPrefix() + RestrictedShop.getInstance().getConfig().getString("message.have-nothing", "&eYou have nothing to sell.")).replace("&", "§"));
                                } else { // 单个出售
                                    int totalSold = 0;
                                    for (ItemStack itemStack : player.getInventory()) {
                                        if (itemStack != null && itemStack.getType().toString().equals(shopItem.getMaterial()) && (itemStack.getItemMeta() == null || !itemStack.getItemMeta().hasCustomModelData() || itemStack.getItemMeta().getCustomModelData() == shopItem.getCustomerModelData())) {
                                            itemStack.setAmount(itemStack.getAmount() - 1);
                                            sellableNumber -= 1;
                                            totalSold += 1;
                                            break;
                                        }
                                    }
                                    if (totalSold > 0) {
                                        double currentPrice = ((double) shopItem.getPriceRange()[1]) - attenuation * ((double) playerData.getSoldNumbers()[index]);
                                        playerData.getSoldNumbers()[index] += 1;
                                        // 发钱
                                        Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), shop.getPayTemplate().replace("{player}", player.getName()).replace("{amount}", new DecimalFormat("#.00").format(currentPrice)));
                                        e.setCurrentItem(ShopCore.generateShopItem(shopItem, sellableNumber, playerData.getSoldNumbers()[index], playerData.getPercentage()));
                                    } else player.sendMessage((RestrictedShop.getInstance().getPrefix() + RestrictedShop.getInstance().getConfig().getString("message.have-nothing", "&eYou have nothing to sell.")).replace("&", "§"));
                                }
                            }
                        }
                    }
                }
            } else player.closeInventory();
        }
    }

    @EventHandler
    public void onInventoryClose(InventoryCloseEvent e) {
        if (ShopCore.TRADING.containsKey(e.getPlayer().getName())) {
            RestrictedShop.getInstance().getStorage().savePlayerData(ShopCore.TRADING.get(e.getPlayer().getName()));
            ShopCore.TRADING.remove(e.getPlayer().getName());
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent e) {
        if (ShopCore.TRADING.containsKey(e.getPlayer().getName())) {
            RestrictedShop.getInstance().getStorage().savePlayerData(ShopCore.TRADING.get(e.getPlayer().getName()));
            ShopCore.TRADING.remove(e.getPlayer().getName());
        }
    }

}
